package vn.com.baseapplication;

import java.io.File;
import java.util.List;

import vn.com.baseapplication.network.BaseNetwork;
import vn.com.baseapplication.network.NetworkHandlerCallback;
import vn.com.baseapplication.service.BaseReceiver;
import vn.com.baseapplication.service.BaseReceiverListener;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.provider.Settings;
import android.provider.Settings.Secure;

import com.nostra13.universalimageloader.cache.disc.impl.LimitedAgeDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public abstract class BaseApplication extends Application implements NetworkHandlerCallback,BaseReceiverListener{
	private static BaseApplication instance;
	
	public static final String NAME_PREF = "vn.com.baseapplication";
	protected static SharedPreferences prefs;
	
	protected BaseNetwork network;
	
	private BaseReceiver baseReceiver = new BaseReceiver(this);
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		instance = this;
		
		prefs = this.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
		
		initImageLoader(getApplicationContext());
		
		network = new BaseNetwork(this);
		
		registerReceiver(baseReceiver, baseReceiver.getIntentFilter());
	}
	
	@Override
	public void onTerminate() {
		unregisterReceiver(baseReceiver);
		super.onTerminate();
	}
	
	public static BaseApplication getInstance(){
		return instance;
	}
	
	@Override
	public void sendBaseBroadcast(Context context, Intent intent) {
		baseReceiver.sendBaseBroadcast(context, intent);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
	}
	
	/**
	 * SharePreferences
	 * */
	public long getValue(String key, long defaultValue) {
		return prefs.getLong(key, defaultValue);
	}

	public int getValue(String key, int defaultValue) {
		return prefs.getInt(key, defaultValue);
	}

	public String getValue(String key, String defaultValue) {
		return prefs.getString(key, defaultValue);
	}

	public float getValue(String key, float defaultValue) {
		return prefs.getFloat(key, defaultValue);
	}

	public void setValue(String key, long value) {
		prefs.edit().putLong(key, value).commit();
	}

	public void setValue(String key, int value) {
		prefs.edit().putInt(key, value).commit();
	}

	public void setValue(String key, String value) {
		prefs.edit().putString(key, value).commit();
	}

	public void setValue(String key, float value) {
		prefs.edit().putFloat(key, value).commit();
	}
	
	public boolean getValue(String key, boolean defaultValue) {
		return prefs.getBoolean(key, defaultValue);
	}

	public void setValue(String key, boolean value) {
		prefs.edit().putBoolean(key, value).commit();
	}
	
	/**
	 * Configuration
	 * */
	public String getDeviceId(){
		return Secure.getString(getContentResolver(),Secure.ANDROID_ID);
	}

	public boolean isTablet() {
		return (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}
	
	public String getVersionApp(){
		PackageInfo pInfo;
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			return pInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return "1.0";
	}
	
	public double[] getGPS() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
        List<String> providers = lm.getProviders(true);

        /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
        Location l = null;
        
        for (int i=providers.size()-1; i>=0; i--) {
                l = lm.getLastKnownLocation(providers.get(i));
                if (l != null) break;
        }
        
        double[] gps = new double[2];
        if (l != null) {
                gps[0] = l.getLatitude();
                gps[1] = l.getLongitude();
        }
        return gps;
}
	
	/**
	 * Loader Image init
	 * */
	public void initImageLoader(Context context) {
		// create folder to cache inmage
		File cacheDir;
		// check if
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					"boo/cache");
		} else {
			cacheDir = context.getCacheDir();
		}

		// if cacheDir is not exists
		if (!cacheDir.isDirectory()) {
			cacheDir.mkdirs();
		}
		
		// create display options
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.cacheInMemory(true)
				.cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				.discCache(new LimitedAgeDiscCache(cacheDir, 30400))
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
//				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.discCacheExtraOptions(480, 800, CompressFormat.PNG, 75, null)
				.defaultDisplayImageOptions(options)
				.build();
		ImageLoader.getInstance().init(config);
	}
	
	/**
	 * Network State Handler
	 * */
	@Override
	public void onNetLoading(int requestId) {
	}
	
	@Override
	public void onNetSuccess(int requestId, String response) {
	}
	
	public void onNetSuccessCache(int requestId, String response) {
	}
	
	@Override
	public void onNetFailed(int requestId, String error) {
	}
	
	@Override
	public void onNetTimeOut(int requestId, Throwable error) {
	}
	
	public static boolean haveInternet(Context ctx) {

	    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
	            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

	    if (info == null || !info.isConnected()) {
	        return false;
	    }
	    if (info.isRoaming()) {
	        // here is the roaming option you can change it if you want to
	        // disable internet while roaming, just return false
	        return true;
	    }
	    return true;
	}
	
	public static void showNoConnectionDialog(Context ctx1) {
        final Context ctx = ctx1;
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setCancelable(true);
        builder.setMessage(R.string.no_connection);
        builder.setTitle(R.string.no_connection_title);
        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                return;
            }
        });

        builder.show();
    }
}
